<template>
  <div >
  <!-- 返回按钮 -->
      <div class="back-button">
        <el-button type="text" @click="goBack" icon="el-icon-arrow-left">
          返回帖子列表
        </el-button>
      </div>
      <div class="post-form">
        <h2>发布帖子</h2>

        <!-- 标题输入框 -->
        <el-input
          v-model="postForm.title"
          placeholder="请输入标题 (至少5个字)"
          :maxlength="50"
          show-word-limit
          clearable
        ></el-input>

        <WangEditor
          v-model="postForm.content"
          :enable-markdown="true"
          :upload-img-server="'http://localhost:8080/common/minio/upload'"
        />
        <div class="upload-and-select-container">
        <!-- 图片上传组件 -->
        <el-upload
          action="http://localhost:8080/common/minio/upload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-success="handleUploadSuccess"
          :before-upload="beforeUpload"
          :limit="1"
          :on-exceed="handleExceed"
        >
          <i class="el-icon-plus"></i>
        </el-upload>

        <el-dialog :visible.sync="dialogVisible" append-to-body>
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
        <!-- 帖子分类下拉框 -->
        <el-select v-model="postForm.categoryId" placeholder="请选择帖子分类" style="margin-top: 20px;"  prop="categoryId">
          <el-option
            v-for="item in categories"
            :key="item.categoryId"
            :label="item.name"
            :value="item.categoryId"
          ></el-option>
        </el-select>

      </div>
        <!-- 发布按钮 -->
        <el-button type="success" round class="post-button" @click="submitPost" :loading="loading">发布</el-button>
      </div>
  </div>
</template>

<script>
// 富文本样式
import '@wangeditor/editor/dist/css/style.css'
import WangEditor from "@/components/WangEditor.vue";
import { addPosts } from '@/api/forum/posts';
import { listCategory } from '@/api/forum/category';

export default {
  name:'PostForm',
  components: {
    WangEditor,
  },
  data() {
    return {
      postForm: {
        title: '',
        content: '',
        categoryId: null,
        imageUrl: ''
      },
      dialogImageUrl: '',
      dialogVisible: false,
      categories: [],
      loading: false,
    };
  },
  created() {
    this.loadCategories();
  },
  methods: {
    loadCategories() {
      listCategory().then(response => {
        this.categories = response.rows;
      });
    },

    // el-upload 成功回调
    handleUploadSuccess(response, file) {
      if (response.code === 200) {
        this.postForm.imageUrl = response.data.url;
        this.$message.success('封面上传成功!');
      } else {
        this.$message.error('封面上传失败: ' + response.msg);
      }
    },

    beforeUpload(file) {
      const isValidType = ['image/jpeg', 'image/png', 'image/gif'].includes(file.type);
      if (!isValidType) {
        this.$message.error('只能上传 JPG/PNG/GIF 格式的图片');
        return false;
      }
      return true;
    },

    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    handleExceed(files, fileList) {
      this.$message.warning(`封面只能上传一张图片`);
    },

    submitPost() {
      if (!this.postForm.title || this.postForm.title.length < 5) {
        this.$message.error('标题至少需要5个字');
        return;
      }
      if (!this.postForm.content) {
        this.$message.error('请输入帖子内容');
        return;
      }
      if (!this.postForm.categoryId) {
        this.$message.error('请选择帖子分类');
        return;
      }

      this.loading = true;
      addPosts(this.postForm).then(response => {
        this.$message.success('帖子发布成功！');
        this.$router.push({ name: 'first' });
      }).finally(() => {
        this.loading = false;
      });
    },
    // 返回上一页
    goBack() {
      // 如果历史记录中有上一页，则返回，否则跳转到首页
      if (window.history.length > 1) {
        this.$router.go(-1);
      } else {
        this.$router.push({ name: 'first' }).catch(err => {
          if (err.name === 'NavigationDuplicated') {
            console.log('重复导航被忽略');
            return;
          }
          throw err;
        });
      }
    },
  }
};
</script>

<style scoped>
.post-form {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.post-form h2 {
    text-align: center;
    margin-bottom: 25px;
}

.post-button {
  margin-top: 20px;
  display: block;
  width: 100%;
}

.upload-and-select-container {
  display: flex;
  align-items: center; /* 垂直居中 */
  gap: 10px; /* 元素之间间距为10px */
  flex-wrap: wrap; /* 可选：自动换行，适配小屏幕 */
}
</style>
